package jobs;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import models.Enseignant;
import models.Formation;
import models.Intervention;

import controllers.Interventions;
import controllers.MyWebSocket;
import play.cache.Cache;
import play.jobs.Job;
import play.jobs.OnApplicationStart;
import utils.ControlData;
import utils.POIExcelReader;

public class NotificationJob extends Job {
	
	Map<Integer, List<String>> datas;

	public NotificationJob(Map<Integer, List<String>> datas) {
		this.datas = datas;
	}

	public void doJob() {
		boolean existError = false;
		for(int i = 1; i <= datas.size(); i++){
			List<String> dataLine = datas.get(i);
			String erreurs = null;
			try {
				erreurs = POIExcelReader.checkDataRecovered(dataLine);				
				MyWebSocket.liveStream.publish(erreurs);
				Thread.sleep(2000);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
				if(!erreurs.isEmpty())
					existError = true;
		}
		if(!existError){
			Enseignant createdBy = (Enseignant) Cache.get("user");
			
			for(List<String> dataLine : datas.values()){
				Formation formationRecovered = null;
				for(Formation formation : Interventions.listFormationToUpdate){
					if(formation.libelleFormation.compareToIgnoreCase(dataLine.get(2)) == 0)
						formationRecovered = formation;
				}
				Intervention interventionToCreate = new Intervention(dataLine.get(0), dataLine.get(1), ControlData.parseToDate(dataLine.get(4)), 
						ControlData.parseToDate(dataLine.get(3)), Integer.valueOf(dataLine.get(5)), formationRecovered, createdBy);
				interventionToCreate.createdAt = new Date();
				interventionToCreate.save();
			}			
		}
		datas.clear();
    }
}
